package com.example.a02back.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import org.springframework.web.multipart.MultipartFile;


/**
 * @ClassName FileUtils
 * @Description
 * @Author SimpChaos
 * @Date 2022/7/11 9:54
 * @Version 1.0
 **/
public class FileUtils {

    public static String upload(MultipartFile File, String uid,String sid) throws IOException{
        List<String> l = new ArrayList<>();
            String fileName = File.getOriginalFilename();
            byte[] bytes = File.getBytes();
            String key = RandomUtil.randomNumbers(20);
            String uniqueId = uid;
            File folder = new File("./filefolder/"+uniqueId+"/");
            System.out.println(folder.getAbsolutePath());
            if(!folder.exists()) folder.mkdirs();
            File newFile = new File(folder,key+fileName);
            l.add(newFile.getPath());
            OutputStream out = new FileOutputStream(newFile);
            out.write(bytes);
            out.flush();
            out.close();

        return newFile.getPath();

		/*
		String filePath = "C:\\Users\\SimpleChris\\A01\\five-twist-a01\\AOI_BACK\\file\\" + key + "-" + fileName;
		File dest = new File(filePath);
		System.out.println(dest.getAbsolutePath());
		file.transferTo(dest);
		return APIResponse.success("成功传入");*/
    }




    public static void download(String path,HttpServletResponse response) throws IOException{
        File file=new File(path);
        FileInputStream fis=new FileInputStream(file);
        byte[] buffer=new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
        response.addHeader("Content-Length",""+file.length());
        OutputStream out=new BufferedOutputStream(response.getOutputStream());
        response.setContentType("applicaation/octet-stream");
        out.write(buffer);
        out.flush();
        out.close();
    }

}
